const { USER_LIST_SORT_SET } = require('../../../consts/system')

const { Success, SysErr } = require('../../../response/code')

const { createRedisClient } = require('../../../util/redis')

const { TOKEN_PREFIX } = require('../../../consts/system')

const moment = require('moment')

class SysUserOnlineService {
  async del(ctx) {
    try {
      const body = ctx.request.body
      const conn = createRedisClient() // 创建新的 Redis 客户端实例
      await conn.connect() // 连接 Redis
      const result = await conn.zRem(USER_LIST_SORT_SET, body.phone)
      const remove = await conn.expire(`${TOKEN_PREFIX}:${body.phone}`, 0) // 设置过期时间,通过监听key过滤删除数据
      await conn.close()

      ctx.body = new Success(result == 1 && remove == 1).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }

  async list(ctx) {
    try {
      const query = ctx.request.query
      const offset = (query.pageNo - 1) * query.pageSize

      const conn = createRedisClient() // 创建新的 Redis 客户端实例
      await conn.connect() // 连接 Redis
      const data = await conn.zRangeWithScores(
        USER_LIST_SORT_SET,
        offset,
        query.pageSize
      )
      const total = await conn.zCount(USER_LIST_SORT_SET, '-inf', '+inf')

      await conn.close()

      let list = []
      data.forEach((user) => {
        list.push({
          phone: user.value,
          login_time: moment(user.score).format('YYYY-MM-DD HH:mm:ss'),
        })
      })
      const result = {
        list: list,
        count: total,
      }
      ctx.body = new Success(result).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }
}

module.exports = new SysUserOnlineService()
